import React, { useState, useEffect } from 'react';
import { Calendar, Clock, User, FileText, Download, Loader2, AlertCircle, CheckCircle, FolderOpen, Settings, Copy, GitBranch, Edit3, Eye, Code, GitCommit, X } from 'lucide-react';
import { Card, Row, Col, Button, Spin, Empty, Typography, Tooltip, App } from 'antd';
import { CheckOutlined, TagOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

const { Text } = Typography;
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { LocalStorageService } from '../services/LocalStorageService';
import { ReportService, ReportType, GeneratedReport } from '../services/ReportService';
import { GitService } from '../services/GitService';
import { ProjectConfig, AIProvider } from '../types';
import ApiService from '../services/ApiService';
import { ConfigService } from '../services/ConfigService';
import { ManualReportGenerator } from './ManualReportGenerator';
import { useToast } from '../contexts/ToastContext';
import { cleanMarkdownContent } from '../lib/utils';

interface ReportGeneratorProps {
  selectedProject: ProjectConfig | null;
}

export const ReportGeneratorNew: React.FC<ReportGeneratorProps> = ({ selectedProject }) => {
  // 初始化默认日期
  const getDefaultDates = () => {
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    return { startDate: todayStr, endDate: todayStr };
  };
  
  const defaultDates = getDefaultDates();
  
  const [reportType, setReportType] = useState<ReportType>('daily');
  const [startDate, setStartDate] = useState(defaultDates.startDate);
  const [endDate, setEndDate] = useState(defaultDates.endDate);
  const [selectedAuthor, setSelectedAuthor] = useState('');
  const [authors, setAuthors] = useState<string[]>([]);
  const [reportStyle, setReportStyle] = useState<'simple' | 'professional'>('simple');
  const [reportFormat, setReportFormat] = useState<'markdown' | 'text'>('markdown');
  const [includeDiff, setIncludeDiff] = useState<boolean>(false);
  const [customPrompt, setCustomPrompt] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [config, setConfig] = useState<any>(null);
  const [generatedReport, setGeneratedReport] = useState<GeneratedReport | null>(null);
  const [availableProjects, setAvailableProjects] = useState<ProjectConfig[]>([]);
  const [currentProject, setCurrentProject] = useState<ProjectConfig | null>(selectedProject);
  const [loadingProjects, setLoadingProjects] = useState(false);
  const [reportMode, setReportMode] = useState<'git' | 'manual' | 'git-custom'>('git');
  const [previewMode, setPreviewMode] = useState<'raw' | 'markdown'>('raw');
  
  // Git自选模式相关状态
  const [customReportType, setCustomReportType] = useState<'daily' | 'weekly'>('daily');
  const [authorCommits, setAuthorCommits] = useState<any[]>([]);
  const [selectedCommits, setSelectedCommits] = useState<string[]>([]);
  const [loadingCommits, setLoadingCommits] = useState(false);
  
  const { showToast } = useToast();
  const { modal } = App.useApp();

  // 初始化日期
  useEffect(() => {
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    
    if (reportType === 'daily') {
      setStartDate(todayStr);
      setEndDate(todayStr);
    } else if (reportType === 'weekly') {
      const dayOfWeek = today.getDay(); // 0=周日, 1=周一, ..., 6=周六
      // 计算本周一的日期 - 如果是周日，往前推6天到周一；否则计算到周一的偏移
      const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
      const startOfWeek = new Date(today.getTime() + mondayOffset * 24 * 60 * 60 * 1000);
      
      // 计算本周日的日期 - 周报应该包含完整的一周数据（周一到周日）
      const sundayOffset = dayOfWeek === 0 ? 0 : 7 - dayOfWeek;
      const endOfWeek = new Date(today.getTime() + sundayOffset * 24 * 60 * 60 * 1000);
      
      setStartDate(startOfWeek.toISOString().split('T')[0]);
      setEndDate(endOfWeek.toISOString().split('T')[0]);
    }
  }, [reportType]);

  // 加载项目列表
  useEffect(() => {
    loadAvailableProjects();
    loadConfig();
  }, []);

  const loadConfig = async () => {
    try {
      const appConfig = await ConfigService.getConfig();
      setConfig(appConfig);
      // 加载自定义提示词
      if (appConfig.customPrompts) {
        const savedPrompt = appConfig.customPrompts[reportStyle] || '';
        setCustomPrompt(savedPrompt);
      }
    } catch (error) {
      console.warn('加载配置失败，使用默认配置:', error);
    }
  };

  const saveConfig = async (updates: any) => {
    try {
      const updatedConfig = { ...config, ...updates };
      await ConfigService.saveConfig(updatedConfig);
      // 重新从服务器获取最新配置，确保数据同步
      await loadConfig();
    } catch (error) {
      console.error('保存配置失败:', error);
      showToast({ type: 'error', text: '保存配置失败' });
    }
  };

  // 保存自定义提示词
  const saveCustomPrompt = async () => {
    if (!config) return;
    
    const customPrompts = {
      ...config.customPrompts,
      [reportStyle]: customPrompt
    };
    
    await saveConfig({ customPrompts });
    showToast({ type: 'success', text: '自定义提示词已保存' });
  };

  // 更新当前项目
  useEffect(() => {
    console.log('[ReportGeneratorNew] useEffect selectedProject 变化:', selectedProject);
    console.log('[ReportGeneratorNew] selectedProject 类型:', typeof selectedProject);
    if (selectedProject) {
      console.log('[ReportGeneratorNew] selectedProject.path:', selectedProject.path);
      console.log('[ReportGeneratorNew] selectedProject.path 类型:', typeof selectedProject.path);
      console.log('[ReportGeneratorNew] selectedProject 完整结构:', JSON.stringify(selectedProject, null, 2));
    }
    setCurrentProject(selectedProject);
    console.log('[ReportGeneratorNew] 设置 currentProject 为:', selectedProject);
  }, [selectedProject]);

  // 监听报告风格变化，加载对应的自定义提示词
  useEffect(() => {
    if (config?.customPrompts) {
      const savedPrompt = config.customPrompts[reportStyle] || '';
      setCustomPrompt(savedPrompt);
    }
  }, [reportStyle, config]);

  // 加载项目作者列表
  useEffect(() => {
    if (currentProject) {
      loadProjectAuthors();
    }
  }, [currentProject]);

  const loadAvailableProjects = async () => {
    try {
      setLoadingProjects(true);
      console.log('[ReportGeneratorNew] 开始加载项目列表...');
      
      // 尝试从后端API获取项目列表
      const apiResult = await ApiService.projects.getAll();
      console.log('[ReportGeneratorNew] API响应:', apiResult);
      
      if (apiResult.success && apiResult.data) {
        const projects = apiResult.data.map(p => ({
          id: p.id,
          name: p.name,
          path: p.path,
          description: p.description || '',
          addedAt: p.addedAt || new Date().toISOString()
        }));
        console.log('[ReportGeneratorNew] 转换后的项目列表:', projects);
        setAvailableProjects(projects);
      } else {
        console.warn('[ReportGeneratorNew] API失败，使用本地存储:', apiResult.error);
        // API失败时使用本地存储
        const localProjects = LocalStorageService.getProjects();
        console.log('[ReportGeneratorNew] 本地项目列表:', localProjects);
        setAvailableProjects(localProjects);
      }
    } catch (error) {
      console.error('[ReportGeneratorNew] 加载项目列表失败:', error);
      // 回退到本地存储
      const localProjects = LocalStorageService.getProjects();
      console.log('[ReportGeneratorNew] 回退到本地项目列表:', localProjects);
      setAvailableProjects(localProjects);
    } finally {
      setLoadingProjects(false);
    }
  };

  const handleProjectSelect = (project: ProjectConfig) => {
    setCurrentProject(project);
    LocalStorageService.setSelectedProject(project);
    showToast({ type: 'success', text: `已选择项目: ${project.name}` });
  };

  const handleRemoveProject = (projectId: string, projectName: string) => {
    modal.confirm({
      title: '删除项目',
      content: `确定要删除项目 "${projectName}" 吗？此操作不可撤销。`,
      icon: React.createElement(ExclamationCircleOutlined),
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          // 尝试通过API删除
          const result = await ApiService.projects.remove(projectId);
          if (result.success) {
            // API删除成功，更新本地状态
            setAvailableProjects(prev => prev.filter(p => p.id !== projectId));
            showToast({ type: 'success', text: '项目删除成功' });
          } else {
            // API删除失败，尝试本地删除
            const localResult = await LocalStorageService.removeProject(projectId);
            if (localResult.success) {
              setAvailableProjects(prev => prev.filter(p => p.id !== projectId));
              showToast({ type: 'success', text: '项目删除成功（本地存储）' });
            } else {
              showToast({ type: 'error', text: `删除项目失败: ${localResult.error}` });
            }
          }
        } catch (error) {
          console.error('删除项目失败:', error);
          // API调用失败，尝试本地删除
          try {
            const localResult = await LocalStorageService.removeProject(projectId);
            if (localResult.success) {
              setAvailableProjects(prev => prev.filter(p => p.id !== projectId));
              showToast({ type: 'success', text: '项目删除成功（本地存储）' });
            } else {
              showToast({ type: 'error', text: `删除项目失败: ${localResult.error}` });
            }
          } catch (localError) {
            console.error('本地删除项目失败:', localError);
            showToast({ type: 'error', text: '删除项目失败' });
          }
        }
      }
    });
  };

  const loadProjectAuthors = async () => {
    if (!currentProject) return;
    
    // 添加调试日志
    console.log('[DEBUG] loadProjectAuthors - currentProject:', currentProject);
    console.log('[DEBUG] loadProjectAuthors - currentProject.path:', currentProject.path);
    console.log('[DEBUG] loadProjectAuthors - typeof currentProject.path:', typeof currentProject.path);
    
    // 确保projectPath是字符串类型
    let projectPath: string;
    if (typeof currentProject.path === 'string') {
      projectPath = currentProject.path;
    } else if (currentProject.path && typeof currentProject.path === 'object') {
      // 如果path是对象，尝试获取其字符串表示
      projectPath = String(currentProject.path);
      console.warn('[DEBUG] loadProjectAuthors - path是对象，转换为字符串:', projectPath);
    } else {
      console.error('[DEBUG] loadProjectAuthors - 无效的path类型:', typeof currentProject.path, currentProject.path);
      return;
    }
    
    console.log('[DEBUG] loadProjectAuthors - 最终使用的projectPath:', projectPath);
    
    try {
      const result = await LocalStorageService.getProjectAuthors(projectPath);
      if (result.success && result.data) {
        setAuthors(result.data);
      }
    } catch (error) {
      console.error('加载作者列表失败:', error);
    }
  };

  // 获取指定作者的所有提交记录
  const loadAuthorCommits = async (author: string) => {
    if (!currentProject || !author) return;
    
    // 添加调试日志
    console.log('[DEBUG] loadAuthorCommits - currentProject:', currentProject);
    console.log('[DEBUG] loadAuthorCommits - currentProject.path:', currentProject.path);
    console.log('[DEBUG] loadAuthorCommits - typeof currentProject.path:', typeof currentProject.path);
    console.log('[DEBUG] loadAuthorCommits - author:', author);
    
    // 确保projectPath是字符串类型
    let projectPath: string;
    if (typeof currentProject.path === 'string') {
      projectPath = currentProject.path;
    } else if (currentProject.path && typeof currentProject.path === 'object') {
      // 如果path是对象，尝试获取其字符串表示
      projectPath = String(currentProject.path);
      console.warn('[DEBUG] loadAuthorCommits - path是对象，转换为字符串:', projectPath);
    } else {
      console.error('[DEBUG] loadAuthorCommits - 无效的path类型:', typeof currentProject.path, currentProject.path);
      return;
    }
    
    console.log('[DEBUG] loadAuthorCommits - 最终使用的projectPath:', projectPath);
    
    setLoadingCommits(true);
    try {
      const result = await ApiService.git.getCommits(projectPath, {
        author: author,
        maxCount: 100, // 获取最近100条提交
        includeDiff: false // 先不包含diff，提高加载速度
      });
      
      if (result.success && result.data) {
        setAuthorCommits(result.data);
      } else {
        console.warn('获取提交记录失败:', result.error);
        setAuthorCommits([]);
      }
    } catch (error) {
      console.error('加载提交记录异常:', error);
      setAuthorCommits([]);
    } finally {
      setLoadingCommits(false);
    }
  };

  // 处理作者选择变化
  const handleAuthorChange = (author: string) => {
    setSelectedAuthor(author);
    setSelectedCommits([]); // 清空已选择的提交
    if (author) {
      loadAuthorCommits(author);
    } else {
      setAuthorCommits([]);
    }
  };

  // 处理提交记录选择
  const handleCommitToggle = (commitHash: string) => {
    setSelectedCommits(prev => {
      if (prev.includes(commitHash)) {
        return prev.filter(hash => hash !== commitHash);
      } else {
        return [...prev, commitHash];
      }
    });
  };

  // 全选/取消全选提交记录
  const handleSelectAllCommits = () => {
    if (selectedCommits.length === authorCommits.length) {
      setSelectedCommits([]);
    } else {
      setSelectedCommits(authorCommits.map(commit => commit.hash));
    }
  };



  // 日期格式验证函数
  const validateDate = (dateStr: string): boolean => {
    if (!dateStr) return false;
    const date = new Date(dateStr);
    return !isNaN(date.getTime()) && !!dateStr.match(/^\d{4}-\d{2}-\d{2}$/);
  };

  // 确保日期格式正确
  const ensureValidDate = (dateStr: string): string => {
    if (!dateStr) {
      const today = new Date();
      return today.toISOString().split('T')[0];
    }
    
    if (validateDate(dateStr)) {
      return dateStr;
    }
    
    // 尝试解析并格式化日期
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) {
      return date.toISOString().split('T')[0];
    }
    
    // 如果都失败了，返回今天的日期
    const today = new Date();
    return today.toISOString().split('T')[0];
  };

  const generateReport = async () => {
    if (!currentProject) {
      showToast({ type: 'error', text: '请先选择一个项目' });
      return;
    }

    if (!config?.aiConfig?.apiKey?.trim()) {
      showToast({ type: 'error', text: '请先在系统配置中配置AI API密钥' });
      return;
    }

    // Git自选模式的验证
    if (reportMode === 'git-custom') {
      if (!selectedAuthor) {
        showToast({ type: 'error', text: '请先选择作者' });
        return;
      }
      if (selectedCommits.length === 0) {
        showToast({ type: 'error', text: '请至少选择一个提交记录' });
        return;
      }
    }

    if (reportType === 'custom' && (!startDate || !endDate)) {
      showToast({ type: 'error', text: '自定义报告需要指定开始和结束日期' });
      return;
    }

    // 验证日期格式
    if (reportType === 'custom') {
      if (!validateDate(startDate)) {
        showToast({ type: 'error', text: '开始日期格式无效，请选择有效的日期' });
        return;
      }
      if (!validateDate(endDate)) {
        showToast({ type: 'error', text: '结束日期格式无效，请选择有效的日期' });
        return;
      }
      if (new Date(startDate) > new Date(endDate)) {
        showToast({ type: 'error', text: '开始日期不能晚于结束日期' });
        return;
      }
    }

    setIsGenerating(true);
    setGeneratedReport(null); // 清空之前的报告，确保显示联动效果

    try {
      // 详细的调试日志
      console.log('[ReportGeneratorNew] 开始生成报告');
      console.log('[ReportGeneratorNew] 当前配置:', {
        config: config,
        hasConfig: !!config,
        hasAiConfig: !!config?.aiConfig,
        aiConfigKeys: config?.aiConfig ? Object.keys(config.aiConfig) : [],
        aiProvider: config?.aiConfig?.provider,
        hasApiKey: !!config?.aiConfig?.apiKey,
        apiKeyLength: config?.aiConfig?.apiKey?.length || 0,
        apiKeyTrimmed: config?.aiConfig?.apiKey?.trim()?.length || 0,
        reportMode,
        selectedCommits: reportMode === 'git-custom' ? selectedCommits : undefined
      });
      
      // 确保projectPath是字符串类型
      let projectPath: string;
      if (typeof currentProject.path === 'string') {
        projectPath = currentProject.path;
      } else if (currentProject.path && typeof currentProject.path === 'object') {
        // 如果path是对象，尝试获取其字符串表示
        projectPath = String(currentProject.path);
        console.warn('[DEBUG] generateReport - path是对象，转换为字符串:', projectPath);
      } else {
        console.error('[DEBUG] generateReport - 无效的path类型:', typeof currentProject.path, currentProject.path);
        showToast({ type: 'error', text: '项目路径无效，请重新选择项目' });
        return;
      }
      
      console.log('[ReportGeneratorNew] 生成报告参数:', {
        projectPath: projectPath,
        type: reportMode === 'git-custom' ? customReportType : reportType,
        style: reportStyle,
        format: reportFormat,
        includeDiff: includeDiff,
        hasCustomPrompt: !!customPrompt?.trim(),
        aiConfig: config.aiConfig,
        selectedCommits: reportMode === 'git-custom' ? selectedCommits : undefined
      });
      
      // 确保日期格式正确
      const validStartDate = reportType === 'custom' ? ensureValidDate(startDate) : undefined;
      const validEndDate = reportType === 'custom' ? ensureValidDate(endDate) : undefined;
      
      console.log('[ReportGeneratorNew] 处理后的日期:', {
        originalStartDate: startDate,
        originalEndDate: endDate,
        validStartDate,
        validEndDate
      });
      
      const result = await ReportService.generateReport({
        projectPath: projectPath,
        type: reportMode === 'git-custom' ? customReportType : reportType,
        startDate: validStartDate,
        endDate: validEndDate,
        author: selectedAuthor || undefined,
        style: reportStyle,
        format: reportFormat,
        includeDiff,
        customPrompt: customPrompt.trim() || undefined,
        aiConfig: config.aiConfig,
        multiAIConfig: config.multiAIConfig, // 添加多AI配置支持
        selectedCommits: reportMode === 'git-custom' ? selectedCommits : undefined
      });

      console.log('[ReportGeneratorNew] ReportService返回结果:', {
        success: result.success,
        hasData: !!result.data,
        error: result.error,
        dataKeys: result.data ? Object.keys(result.data) : []
      });

      if (result.success && result.data) {
        setGeneratedReport(result.data);
        showToast({ type: 'success', text: '报告生成成功！' });
      } else {
        console.error('[ReportGeneratorNew] 报告生成失败:', result.error);
        showToast({ type: 'error', text: result.error || '报告生成失败' });
      }
    } catch (error) {
      console.error('[ReportGeneratorNew] 报告生成异常:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined
      });
      showToast({ type: 'error', text: `报告生成失败: ${error instanceof Error ? error.message : '未知错误'}` });
    } finally {
      setIsGenerating(false);
    }
  };

  const downloadReport = () => {
    if (!generatedReport) return;

    // 根据reportFormat选择正确的MIME类型和文件扩展名
    const mimeType = reportFormat === 'markdown' ? 'text/markdown;charset=utf-8' : 'text/plain;charset=utf-8';
    const fileExtension = reportFormat === 'markdown' ? '.md' : '.txt';
    const formatText = reportFormat === 'markdown' ? 'MD' : 'TXT';
    
    const blob = new Blob([generatedReport.content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${generatedReport.title}_${formatText}${fileExtension}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const copyToClipboard = async () => {
    if (!generatedReport) return;

    try {
      await navigator.clipboard.writeText(generatedReport.content);
      showToast({ type: 'success', text: '报告内容已复制到剪贴板' });
    } catch (error) {
      showToast({ type: 'error', text: '复制失败，请手动复制' });
    }
  };

  // 如果没有当前项目且有可用项目，显示项目选择界面
  if (!currentProject && availableProjects.length > 0) {
    return (
      <div className="max-w-6xl mx-auto p-8">
        <div className="bg-white border border-neutral-200 rounded-3xl p-8 shadow-strong animate-fade-in">
          <h3 className="text-2xl font-bold mb-6 flex items-center text-neutral-900">
            <FolderOpen className="h-8 w-8 mr-3 text-primary-600" />
            选择项目
          </h3>
          <p className="text-neutral-600 mb-8 text-lg">请选择要生成报告的项目：</p>
          
          {loadingProjects ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin mr-3 text-primary-600" />
              <span className="text-lg font-medium text-neutral-700">加载项目列表...</span>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-6">
              {availableProjects.map((project) => (
                <Card
                  key={project.id}
                  className="relative group h-full transition-all duration-300 hover:shadow-xl border border-gray-200 hover:border-primary-300 rounded-xl overflow-hidden bg-white"
                  style={{ minWidth: '320px' }}
                  styles={{
                    body: { padding: '24px', height: '100%' }
                  }}
                >
                  {/* 删除按钮 */}
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRemoveProject(project.id, project.name);
                    }}
                    className="absolute top-3 right-3 w-8 h-8 bg-red-500 hover:bg-red-600 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-110 z-10"
                    title="删除项目"
                  >
                    <X className="w-4 h-4" />
                  </button>
                  {/* 项目图标和基本信息 */}
                  <div className="flex items-start space-x-4 mb-4">
                    <div className="flex-shrink-0 w-12 h-12 bg-primary-100 rounded-xl flex items-center justify-center shadow-sm">
                      <FolderOpen className="w-6 h-6 text-primary-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <h3 className="text-lg font-semibold text-gray-900 truncate mb-1" title={project.name}>
                        {project.name}
                      </h3>
                      <p className="text-sm text-gray-500 truncate" title={project.path}>
                        {project.path}
                      </p>
                    </div>
                  </div>

                  {/* 项目描述 */}
                  {project.description && (
                    <div className="mb-4">
                      <p className="text-sm text-gray-600 line-clamp-2" title={project.description}>
                        {project.description}
                      </p>
                    </div>
                  )}

                  {/* 项目统计信息 */}
                  <div className="flex items-center justify-between text-xs text-gray-500 mb-6">
                    <span className="flex items-center">
                      <Calendar className="w-3 h-3 mr-1" />
                      {new Date(project.addedAt).toLocaleDateString()}
                    </span>
                    <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full font-medium">
                      活跃
                    </span>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex mt-auto">
                    <Button
                      type="primary"
                      size="middle"
                      icon={<CheckOutlined />}
                      onClick={() => handleProjectSelect(project)}
                      className="w-full h-10 rounded-lg font-medium shadow-sm hover:shadow-md transition-all duration-200"
                    >
                      选择项目
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }

  // 如果没有项目，显示空状态
  if (!currentProject && availableProjects.length === 0) {
    return (
      <div className="max-w-6xl mx-auto p-8">
        <div className="text-center py-16 animate-fade-in">
          <div className="w-24 h-24 bg-neutral-100 rounded-full flex items-center justify-center mx-auto mb-6 shadow-medium">
            <FolderOpen className="h-12 w-12 text-neutral-400" />
          </div>
          <h3 className="text-2xl font-bold text-neutral-900 mb-3">暂无项目</h3>
          <p className="text-neutral-600 mb-8 text-lg max-w-md mx-auto">请先在项目管理中添加项目，然后再生成报告。</p>
          <button
            onClick={() => window.location.href = '/projects'}
            className="inline-flex items-center px-8 py-4 bg-primary-600 text-white rounded-2xl hover:bg-primary-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105 font-semibold text-lg"
          >
            <FolderOpen className="h-6 w-6 mr-3" />
            添加项目
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-full mx-auto p-4">


        {/* 页面标题和当前项目信息 */}
        <div className="mb-4">
          <div className="bg-blue-600 rounded-xl p-3 text-white shadow-lg">
            <div className="flex items-center justify-between">
              <div>
                <h1 className="text-lg font-bold mb-1 flex items-center">
                  <FileText className="h-5 w-5 mr-2" />
                  智能报告生成器
                </h1>
                <div className="flex items-center space-x-3 text-blue-100">
                  <div className="flex items-center">
                    <FolderOpen className="h-3 w-3 mr-1" />
                    <span className="font-medium text-xs">{currentProject.name}</span>
                  </div>
                  <div className="text-xs opacity-90 truncate">{currentProject.path}</div>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                {/* 模式切换器 */}
                <div className="flex bg-white/20 rounded-lg p-1 backdrop-blur-sm border border-white/20">
                  <button
                    onClick={() => setReportMode('git')}
                    className={`px-3 py-1 rounded-md text-xs font-medium transition-all duration-300 flex items-center ${
                      reportMode === 'git'
                        ? 'bg-white text-blue-600 shadow-sm'
                        : 'text-white/80 hover:text-white hover:bg-white/10'
                    }`}
                  >
                    <GitBranch className="h-3 w-3 mr-1" />
                    Git模式
                  </button>
                  <button
                    onClick={() => setReportMode('git-custom')}
                    className={`px-3 py-1 rounded-md text-xs font-medium transition-all duration-300 flex items-center ${
                      reportMode === 'git-custom'
                        ? 'bg-white text-blue-600 shadow-sm'
                        : 'text-white/80 hover:text-white hover:bg-white/10'
                    }`}
                  >
                    <GitBranch className="h-3 w-3 mr-1" />
                    Git自选模式
                  </button>
                  <button
                    onClick={() => setReportMode('manual')}
                    className={`px-3 py-1 rounded-md text-xs font-medium transition-all duration-300 flex items-center ${
                      reportMode === 'manual'
                        ? 'bg-white text-blue-600 shadow-sm'
                        : 'text-white/80 hover:text-white hover:bg-white/10'
                    }`}
                  >
                    <Edit3 className="h-3 w-3 mr-1" />
                    手动模式
                  </button>
                </div>
                <button
                  onClick={() => setCurrentProject(null)}
                  className="bg-white/20 hover:bg-white/30 text-white px-3 py-1.5 rounded-lg transition-all duration-300 backdrop-blur-sm border border-white/20 font-medium text-xs transform hover:scale-105"
                >
                  切换项目
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* 根据模式显示不同的界面 */}
        {reportMode === 'manual' ? (
          <ManualReportGenerator 
            selectedProject={currentProject}
            config={config}
          />
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-8 gap-4 h-screen">

            {/* 左侧：报告配置 */}
            <div className="lg:col-span-3">
            <div className="bg-white border border-neutral-200 rounded-xl p-3 shadow-medium h-screen overflow-hidden flex flex-col">
              <h2 className="text-lg font-bold mb-3 text-neutral-900 flex items-center flex-shrink-0">
                <Settings className="h-5 w-5 mr-2 text-primary-600" />
                配置
              </h2>
              
              {/* 生成按钮 */}
              <div className="flex-shrink-0 mb-3">
                <button
                  onClick={generateReport}
                  disabled={isGenerating}
                  className="w-full bg-primary-600 text-white py-3 px-4 rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center shadow-lg transition-all duration-300 transform hover:scale-105 font-semibold text-sm"
                >
                  {isGenerating ? (
                    <>
                      <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                      生成中...
                    </>
                  ) : (
                    <>
                      <FileText className="h-5 w-5 mr-2" />
                      生成报告
                    </>
                  )}
                </button>
              </div>
              
              <div className="flex-1 overflow-y-auto space-y-3">
                {reportMode === 'git-custom' ? (
                  // Git自选模式的配置
                  <>
                    {/* 报告类型选择 */}
                    <div>
                      <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                        <FileText className="h-4 w-4 mr-1 text-primary-600" />
                        报告类型
                      </label>
                      <div className="grid grid-cols-2 gap-2">
                        <button
                          onClick={() => setCustomReportType('daily')}
                          className={`p-3 rounded-lg border transition-all duration-300 flex flex-col items-center justify-center group ${
                            customReportType === 'daily'
                              ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                              : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                          }`}
                        >
                          <div className="text-sm font-medium text-center">📅 日报</div>
                          <div className="text-xs text-neutral-500 mt-1">日常工作汇报</div>
                        </button>
                        <button
                          onClick={() => setCustomReportType('weekly')}
                          className={`p-3 rounded-lg border transition-all duration-300 flex flex-col items-center justify-center group ${
                            customReportType === 'weekly'
                              ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                              : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                          }`}
                        >
                          <div className="text-sm font-medium text-center">📊 周报</div>
                          <div className="text-xs text-neutral-500 mt-1">周度工作总结</div>
                        </button>
                      </div>
                    </div>

                    {/* 作者选择 */}
                    <div>
                      <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                        <User className="h-4 w-4 mr-1 text-primary-600" />
                        选择作者
                      </label>
                      <select
                        value={selectedAuthor}
                        onChange={(e) => handleAuthorChange(e.target.value)}
                        className="w-full px-3 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md text-sm font-medium"
                      >
                        <option value="">请选择作者</option>
                        {authors.map(author => (
                          <option key={author} value={author}>👤 {author}</option>
                        ))}
                      </select>
                    </div>

                    {/* 提交记录展示和选择 */}
                    {selectedAuthor && (
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <label className="block text-sm font-bold text-neutral-900 flex items-center">
                            <GitCommit className="h-4 w-4 mr-1 text-primary-600" />
                            提交记录 ({authorCommits.length})
                          </label>
                          {authorCommits.length > 0 && (
                            <button
                              onClick={handleSelectAllCommits}
                              className="text-xs text-primary-600 hover:text-primary-700 font-medium"
                            >
                              {selectedCommits.length === authorCommits.length ? '取消全选' : '全选'}
                            </button>
                          )}
                        </div>
                        
                        <div className="border border-neutral-200 rounded-lg max-h-64 overflow-y-auto">
                          {loadingCommits ? (
                            <div className="p-4 text-center">
                              <Loader2 className="h-5 w-5 animate-spin mx-auto mb-2 text-primary-600" />
                              <div className="text-sm text-neutral-600">加载提交记录中...</div>
                            </div>
                          ) : authorCommits.length === 0 ? (
                            <div className="p-4 text-center text-sm text-neutral-500">
                              暂无提交记录
                            </div>
                          ) : (
                            <div className="divide-y divide-neutral-100">
                              {authorCommits.map((commit) => (
                                <label key={commit.hash} className="flex items-start p-3 hover:bg-neutral-50 cursor-pointer">
                                  <input
                                    type="checkbox"
                                    checked={selectedCommits.includes(commit.hash)}
                                    onChange={() => handleCommitToggle(commit.hash)}
                                    className="mt-1 w-4 h-4 text-primary-600 bg-white border-neutral-300 rounded focus:ring-primary-500 focus:ring-2 transition-all duration-300"
                                  />
                                  <div className="ml-3 flex-1 min-w-0">
                                    <div className="text-sm font-medium text-neutral-900 truncate">
                                      {commit.message}
                                    </div>
                                    <div className="flex items-center space-x-2 mt-1 text-xs text-neutral-500">
                                      <span className="font-mono">{commit.hash.substring(0, 7)}</span>
                                      <span>•</span>
                                      <span>{new Date(commit.date).toLocaleDateString()}</span>
                                      {commit.filesChanged && (
                                        <>
                                          <span>•</span>
                                          <span>{commit.filesChanged} 文件</span>
                                        </>
                                      )}
                                    </div>
                                  </div>
                                </label>
                              ))}
                            </div>
                          )}
                        </div>
                        
                        {selectedCommits.length > 0 && (
                          <div className="mt-2 p-2 bg-primary-50 border border-primary-200 rounded-lg">
                            <div className="text-xs text-primary-700">
                              已选择 {selectedCommits.length} 个提交记录
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </>
                ) : (
                  // 原有Git模式的配置
                  <>
                    {/* 报告类型 */}
                    <div>
                      <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                        <FileText className="h-4 w-4 mr-1 text-primary-600" />
                        类型
                      </label>
                      <div className="grid grid-cols-3 gap-1">
                        {[
                          { value: 'daily', label: '📅 日报', desc: '今日工作总结' },
                          { value: 'weekly', label: '📊 周报', desc: '本周进展汇总' },
                          { value: 'custom', label: '🎯 自定义', desc: '指定时间范围' }
                        ].map(({ value, label, desc }) => (
                          <button
                            key={value}
                            onClick={() => setReportType(value as ReportType)}
                            className={`p-2 rounded-lg border transition-all duration-300 flex flex-col items-center justify-center group ${
                              reportType === value
                                ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                                : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                            }`}
                          >
                            <div className="text-xs font-medium text-center">{label}</div>
                            {reportType === value && (
                              <div className="w-2 h-2 bg-primary-500 rounded-full mt-1">
                              </div>
                            )}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* 作者筛选 */}
                    <div>
                      <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                        <User className="h-4 w-4 mr-1 text-primary-600" />
                        作者
                      </label>
                      <select
                        value={selectedAuthor}
                        onChange={(e) => setSelectedAuthor(e.target.value)}
                        className="w-full px-3 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md text-sm font-medium"
                      >
                        <option value="">👥 所有作者</option>
                        {authors.map(author => (
                          <option key={author} value={author}>👤 {author}</option>
                        ))}
                      </select>
                    </div>
                  </>
                )}

                {/* 自定义日期范围 */}
                {reportType === 'custom' && (
                  <div className="bg-primary-50 p-3 rounded-lg border border-primary-200">
                    <h4 className="text-sm font-bold text-neutral-900 mb-2 flex items-center">
                      <Calendar className="h-4 w-4 mr-1 text-primary-600" />
                      时间范围
                    </h4>
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="block text-sm font-semibold text-neutral-700 mb-1">
                          开始
                        </label>
                        <input
                          type="date"
                          value={startDate}
                          onChange={(e) => setStartDate(e.target.value)}
                          className="w-full px-2 py-1 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md text-sm font-medium"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-semibold text-neutral-700 mb-1">
                          结束
                        </label>
                        <input
                          type="date"
                          value={endDate}
                          onChange={(e) => setEndDate(e.target.value)}
                          className="w-full px-2 py-1 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md text-sm font-medium"
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* 报告风格 */}
                <div>
                  <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                    <FileText className="h-4 w-4 mr-1 text-primary-600" />
                    风格
                  </label>
                  <div className="grid grid-cols-2 gap-1">
                    <button
                      onClick={() => setReportStyle('simple')}
                      className={`p-2 border rounded-lg cursor-pointer transition-all duration-300 text-left group ${
                        reportStyle === 'simple'
                          ? 'border-primary-500 bg-primary-50 shadow-sm'
                          : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50'
                      }`}
                    >
                      <div className="flex items-center space-x-1">
                        <div className={`w-3 h-3 rounded-md flex items-center justify-center ${
                          reportStyle === 'simple' ? 'bg-primary-100' : 'bg-neutral-100 group-hover:bg-primary-100'
                        }`}>
                          <span className="text-xs">🎯</span>
                        </div>
                        <div className="font-medium text-neutral-900 text-sm">简单</div>
                      </div>
                    </button>
                    <button
                      onClick={() => setReportStyle('professional')}
                      className={`p-2 border rounded-lg cursor-pointer transition-all duration-300 text-left group ${
                        reportStyle === 'professional'
                          ? 'border-primary-500 bg-primary-50 shadow-sm'
                          : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50'
                      }`}
                    >
                      <div className="flex items-center space-x-1">
                        <div className={`w-3 h-3 rounded-md flex items-center justify-center ${
                          reportStyle === 'professional' ? 'bg-primary-100' : 'bg-neutral-100 group-hover:bg-primary-100'
                        }`}>
                          <span className="text-xs">💼</span>
                        </div>
                        <div className="font-medium text-neutral-900 text-sm">专业</div>
                      </div>
                    </button>
                  </div>
                </div>

                {/* 输出格式 */}
                <div>
                  <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                    <FileText className="h-4 w-4 mr-1 text-primary-600" />
                    格式
                  </label>
                  <div className="grid grid-cols-1 gap-1">
                    <button
                      onClick={() => setReportFormat('markdown')}
                      className={`p-2 border rounded-lg cursor-pointer transition-all duration-300 text-left group ${
                        reportFormat === 'markdown'
                          ? 'border-primary-500 bg-primary-50 shadow-sm'
                          : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50'
                      }`}
                    >
                      <div className="flex items-center space-x-1">
                        <div className={`w-3 h-3 rounded-md flex items-center justify-center ${
                          reportFormat === 'markdown' ? 'bg-primary-100' : 'bg-neutral-100 group-hover:bg-primary-100'
                        }`}>
                          <span className="text-xs">📝</span>
                        </div>
                        <div className="font-medium text-neutral-900 text-sm">MD</div>
                      </div>
                    </button>
                    <button
                      onClick={() => setReportFormat('text')}
                      className={`p-2 border rounded-lg cursor-pointer transition-all duration-300 text-left group ${
                        reportFormat === 'text'
                          ? 'border-primary-500 bg-primary-50 shadow-sm'
                          : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50'
                      }`}
                    >
                      <div className="flex items-center space-x-1">
                        <div className={`w-3 h-3 rounded-md flex items-center justify-center ${
                          reportFormat === 'text' ? 'bg-primary-100' : 'bg-neutral-100 group-hover:bg-primary-100'
                        }`}>
                          <span className="text-xs">📄</span>
                        </div>
                        <div className="font-medium text-neutral-900 text-sm">文本</div>
                      </div>
                    </button>
                  </div>
                </div>

                {/* 代码内容 */}
                <div>
                  <label className="block text-sm font-bold text-neutral-900 mb-2 flex items-center">
                    <FileText className="h-4 w-4 mr-1 text-primary-600" />
                    代码内容
                  </label>
                  <div className={`p-2 rounded-lg border transition-all duration-300 ${
                    includeDiff 
                      ? 'bg-orange-50 border-orange-200' 
                      : 'bg-primary-50 border-primary-200'
                  }`}>
                    <label className="flex items-center space-x-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={includeDiff}
                        onChange={(e) => setIncludeDiff(e.target.checked)}
                        className="w-4 h-4 text-primary-600 bg-white border-neutral-300 rounded focus:ring-primary-500 focus:ring-2 transition-all duration-300"
                      />
                      <span className="text-sm font-medium text-neutral-900">包含代码差异</span>
                    </label>
                    {includeDiff && (
                      <div className="mt-2 ml-6 p-2 bg-orange-100 border border-orange-200 rounded-lg">
                        <div className="flex items-center space-x-1">
                            <AlertCircle className="h-3 w-3 text-orange-600" />
                            <span className="text-xs font-medium text-orange-800">Token消耗提醒</span>
                          </div>
                          <p className="text-xs text-orange-700 mt-1">
                            包含代码差异会显著增加Token消耗
                          </p>
                      </div>
                    )}
                  </div>
                </div>

                {/* 自定义提示词 */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="block text-sm font-bold text-neutral-900 flex items-center">
                      <FileText className="h-4 w-4 mr-1 text-primary-600" />
                      提示词
                    </label>
                    <button
                      onClick={saveCustomPrompt}
                      className="px-3 py-1 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-all duration-300 shadow-sm hover:shadow-md font-medium text-sm flex items-center"
                    >
                      <Settings className="h-3 w-3 mr-1" />
                      保存
                    </button>
                  </div>
                  <textarea
                    value={customPrompt}
                    onChange={(e) => setCustomPrompt(e.target.value)}
                    placeholder={`输入自定义提示词以个性化报告内容...`}
                    className="w-full px-3 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md resize-vertical text-sm font-medium"
                    rows={2}
                  />
                </div>

              </div>
            </div>
          </div>

          {/* 右侧：报告展示 */}
          <div className="lg:col-span-5">
            {generatedReport ? (
              <div className="bg-white border border-neutral-200 rounded-xl p-4 shadow-medium h-[700px] overflow-hidden flex flex-col">
                <div className="flex items-center justify-between mb-3 flex-shrink-0">
                  <h3 className="text-xl font-bold text-neutral-900 flex items-center">
                    <FileText className="h-6 w-6 mr-2 text-primary-600" />
                    {generatedReport.title}
                  </h3>
                  <div className="flex space-x-2">
                    <div className="flex bg-neutral-100 rounded-lg p-1">
                      <button
                        onClick={() => setPreviewMode('raw')}
                        className={`px-3 py-1 rounded-md text-sm font-medium transition-all duration-300 flex items-center ${
                          previewMode === 'raw'
                            ? 'bg-white text-neutral-700 shadow-sm'
                            : 'text-neutral-500 hover:text-neutral-700'
                        }`}
                      >
                        <Code className="h-4 w-4 mr-1" />
                        原始
                      </button>
                      <button
                        onClick={() => setPreviewMode('markdown')}
                        className={`px-3 py-1 rounded-md text-sm font-medium transition-all duration-300 flex items-center ${
                          previewMode === 'markdown'
                            ? 'bg-white text-neutral-700 shadow-sm'
                            : 'text-neutral-500 hover:text-neutral-700'
                        }`}
                      >
                        <Eye className="h-4 w-4 mr-1" />
                        预览
                      </button>
                    </div>
                    <button
                       onClick={copyToClipboard}
                       className="px-4 py-2 bg-primary-100 text-primary-700 rounded-lg hover:bg-primary-200 transition-all duration-300 flex items-center shadow-md hover:shadow-lg transform hover:scale-105 font-semibold text-base"
                     >
                       <Copy className="h-5 w-5 mr-2" />
                       复制
                     </button>
                    <button
                      onClick={downloadReport}
                      className="px-4 py-2 bg-success-100 text-success-700 rounded-lg hover:bg-success-200 transition-all duration-300 flex items-center shadow-md hover:shadow-lg transform hover:scale-105 font-semibold text-base"
                    >
                      <Download className="h-5 w-5 mr-2" />
                      下载
                    </button>
                  </div>
                </div>

                {/* 报告统计 */}
                <div className="grid grid-cols-4 gap-3 mb-4 flex-shrink-0">
                  <div className="bg-primary-50 border border-primary-200 rounded-lg p-3 shadow-sm">
                    <div className="text-center">
                      <div className="text-xl font-bold mb-2 text-primary-700">{generatedReport.stats.totalCommits}</div>
                      <div className="text-primary-600 text-sm font-semibold flex items-center justify-center">
                        <FileText className="h-4 w-4 mr-1" />
                        提交
                      </div>
                    </div>
                  </div>
                  <div className="bg-success-50 border border-success-200 rounded-lg p-3 shadow-sm">
                    <div className="text-center">
                      <div className="text-xl font-bold mb-2 text-success-700">{generatedReport.stats.totalFiles}</div>
                      <div className="text-success-600 text-sm font-semibold flex items-center justify-center">
                        <FolderOpen className="h-4 w-4 mr-1" />
                        文件
                      </div>
                    </div>
                  </div>
                  <div className="bg-info-50 border border-info-200 rounded-lg p-3 shadow-sm">
                    <div className="text-center">
                      <div className="text-xl font-bold mb-2 text-info-700">+{generatedReport.stats.totalAdditions}</div>
                      <div className="text-info-600 text-sm font-semibold flex items-center justify-center">
                        <CheckCircle className="h-4 w-4 mr-1" />
                        新增
                      </div>
                    </div>
                  </div>
                  <div className="bg-warning-50 border border-warning-200 rounded-lg p-3 shadow-sm">
                    <div className="text-center">
                      <div className="text-xl font-bold mb-2 text-warning-700">-{generatedReport.stats.totalDeletions}</div>
                      <div className="text-warning-600 text-sm font-semibold flex items-center justify-center">
                        <AlertCircle className="h-4 w-4 mr-1" />
                        删除
                      </div>
                    </div>
                  </div>
                </div>

                {/* 报告内容 */}
                <div className="bg-neutral-50 rounded-lg p-3 border border-neutral-200 shadow-sm flex-1 flex flex-col overflow-hidden">
                  <div className="flex items-center mb-2 flex-shrink-0">
                    <div className="w-3 h-3 bg-danger-500 rounded-full mr-1"></div>
                    <div className="w-3 h-3 bg-warning-500 rounded-full mr-1"></div>
                    <div className="w-3 h-3 bg-success-500 rounded-full mr-1"></div>
                    <span className="text-sm font-bold text-neutral-700 ml-2 flex items-center">
                      <FileText className="h-4 w-4 mr-1 text-primary-600" />
                      内容
                    </span>
                  </div>
                  <div className="prose max-w-none flex-1 overflow-hidden">
                    {previewMode === 'raw' ? (
                      <pre className="whitespace-pre-wrap text-sm bg-white p-4 rounded-lg border border-neutral-200 overflow-auto h-full shadow-medium font-mono leading-relaxed text-neutral-800">
                        {generatedReport.content}
                      </pre>
                    ) : (
                      <div className="bg-white p-4 rounded-lg border border-neutral-200 overflow-auto h-full shadow-medium prose prose-sm max-w-none">
                        <ReactMarkdown remarkPlugins={[remarkGfm]}>
                          {cleanMarkdownContent(generatedReport.content)}
                        </ReactMarkdown>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <div className={`bg-white border rounded-xl p-8 text-center shadow-medium h-screen flex flex-col items-center justify-center transition-all duration-500 ${
                isGenerating 
                  ? 'border-primary-300 bg-primary-50' 
                  : 'border-dashed border-neutral-300'
              }`}>
                <div className={`w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 shadow-medium transition-all duration-500 ${
                  isGenerating 
                    ? 'bg-primary-200 animate-pulse' 
                    : 'bg-primary-100'
                }`}>
                  {isGenerating ? (
                    <Loader2 className="h-8 w-8 text-primary-600 animate-spin" />
                  ) : (
                    <FileText className="h-8 w-8 text-primary-600" />
                  )}
                </div>
                
                {isGenerating ? (
                  <>
                    <h3 className="text-lg font-bold text-primary-800 mb-2">正在生成报告</h3>
                    <p className="text-primary-700 text-sm mb-4 max-w-md mx-auto">
                      {includeDiff ? '正在分析代码变更并生成详细报告...' : '正在分析提交记录并生成报告...'}
                    </p>
                    {includeDiff && (
                      <div className="mb-4 p-3 bg-orange-100 border border-orange-200 rounded-lg max-w-md">
                        <div className="flex items-center justify-center space-x-1 mb-1">
                          <AlertCircle className="h-4 w-4 text-orange-600" />
                          <span className="text-sm font-medium text-orange-800">处理中</span>
                        </div>
                        <p className="text-xs text-orange-700">
                          包含代码差异的报告需要更多时间处理，请耐心等待...
                        </p>
                      </div>
                    )}
                    <div className="flex justify-center space-x-2">
                      <div className="w-3 h-3 bg-primary-500 rounded-full animate-bounce"></div>
                      <div className="w-3 h-3 bg-secondary-500 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                      <div className="w-3 h-3 bg-primary-500 rounded-full animate-bounce" style={{animationDelay: '0.4s'}}></div>
                    </div>
                  </>
                ) : (
                  <>
                    <h3 className="text-lg font-bold text-neutral-900 mb-2">等待生成报告</h3>
                    <p className="text-neutral-600 text-sm mb-4 max-w-md mx-auto">配置完成后，点击"生成"按钮开始生成智能报告</p>
                    <div className="flex justify-center space-x-2">
                      <div className="w-2 h-2 bg-primary-400 rounded-full animate-bounce"></div>
                      <div className="w-2 h-2 bg-secondary-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
                      <div className="w-2 h-2 bg-primary-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                    </div>
                  </>
                )}
               </div>
             )}
          </div>
        </div>
        )}
      </div>
    </div>
  );
};